package com.qfedu.openplateform.order.service.impl;

import com.qfedu.openplateform.common.entity.PopOrderData;
import com.qfedu.openplateform.common.entity.PopOrderItem;
import com.qfedu.openplateform.common.entity.WarehouseProduct;
import com.qfedu.openplateform.order.dao.PopOrderDataMapper;
import com.qfedu.openplateform.order.dao.PopOrderItemMapper;
import com.qfedu.openplateform.order.service.PopOrderDataService;
import com.qfedu.openplateform.stack.service.WarehouseProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class PopOrderDataServiceImpl implements PopOrderDataService {

    @Autowired
    private PopOrderDataMapper popOrderDataMapper;
    @Autowired
    private PopOrderItemMapper popOrderItemMapper;
    @Autowired
    private WarehouseProductService warehouseProductService;

    // 添加订单
    public void addOrderData(PopOrderData orderData) throws Exception {
        popOrderDataMapper.addOrderData(orderData);
        List<PopOrderItem> popOrderItemList = orderData.getPopOrderItemList();
        for (PopOrderItem orderItem :
                popOrderItemList) {
            popOrderItemMapper.addOrderItem(orderItem);
            // TODO 减少库存
            WarehouseProduct product = new WarehouseProduct();
            product.setProductId(Integer.parseInt(orderItem.getSkuId().toString()));
            product.setCurrentCnt(-Integer.parseInt(orderItem.getNum().toString()));
            product.setModifiedTime(new Date());
            boolean b = warehouseProductService.updateCurrentCnt(product);
            if (!b) {
                throw new Exception("库存不足");
            }
        }
    }
}
